import axios from 'axios'
import { Message,MessageBox} from 'element-ui'
import store from '../store'

import { baseUrl,devUrl } from '../../public/config';


//请求地址
//axios.defaults.baseURL = 'http://www.vueadmin.me'


//请求地址环境的切换
if (process.env.NODE_ENV == 'development') { 
   // axios.defaults.baseURL = window.__env.development_api;
   // axios.defaults.baseURL = 'http://127.0.0.1:8080';
   // axios.defaults.baseURL = 'http://api.5188.ch';
   axios.defaults.baseURL =devUrl;
   } else if (process.env.NODE_ENV == 'debug') { 
    axios.defaults.baseURL = '';
   } else if (process.env.NODE_ENV == 'production') { 
    //axios.defaults.baseURL = 'https://wtapi.hk9999z.com/';
   // axios.defaults.baseURL = window.__env.production_api;
   axios.defaults.baseURL =baseUrl;
   }
 
   
//This used for change the api under the public config.json
//    const getBaseUrl = function () {
//    var xhr = new XMLHttpRequest(); 
//    xhr.open('GET', "./config.json",true);
//    xhr.send(null);
//    xhr.onreadystatechange = function () {
//      if (xhr.status === 200 && xhr.readyState === 4) {
//         axios.defaults.baseURL = JSON.parse(xhr.responseText).url
//         console.log("--------Get url------------")
//         console.log(JSON.parse(xhr.responseText).url)
//      }
//    }
//    };
   
//    const getUrl = function () {
//      if (process.env.NODE_ENV === 'development' ) {
//         getBaseUrl()//axios.defaults.baseURL = 'http://127.0.0.1:8080'
//      } else {
//         getBaseUrl()
//      }
//    }
//   getUrl() 
//设置超时时间
axios.defaults.timeout = 500000
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.withcredentials = true


//请求拦截(请求发出前处理请求)
axios.interceptors.request.use((config) => {
    const token = localStorage.getItem("adminToken")
    if(token){
        config.headers['Authorization'] =  token 
    }
    return config;
  }, (error) => {
    return Promise.reject(error);
  });

// 响应拦截器（处理响应数据）
axios.interceptors.response.use(
    (res) => {
        const ret = res.data
        
        if(ret.status !== 200 && !ret.key && !ret.code){
            if(ret.status == 101 || ret.status==401){
                MessageBox.confirm(ret.msg, '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }
                ).then(() => {
                    store.dispatch('logout').then(() => {
                        location.href = '/';
                    })
                })
            }else{
                Message({
                    showClose: true,
                    message: ret.msg || 'Server error',
                    type: 'error',
                    duration: 2000
                })
            }
            reject(ret.msg)
        }
        return res
    }, 
    (error) => {
        Message({
            showClose: true,
            message: error.message,
            type: 'error',
            duration: 2000
        })
        return Promise.reject(error);
    }
);

// 封装get方法
function get(url, data){
    return new Promise((resolve, reject) =>{
        axios.get(url, data).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

// 封装post方法
function post(url, params){
    return new Promise((resolve, reject) =>{
        axios.post(url, params).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

//对外接口
export function request({url,method, data}){
    if(method == 'get'){
        return get(url, data);
    }else if(method == 'post'){
        return post(url, data);
    }
}

export default request